var win;
var currentId;

$(document).keypress(function (e) {
	var key = String.fromCharCode(e.which);
	if(key == 'n' && win != null && win != 'undefined' && currentId != null){
		// next
		console.info("currentId"+currentId);
		var newId = getId(2,currentId);
            	if(newId == null || newId == '' || newId == 'null'){
            		Ext.example.msg('', '无数据', '');
            	}else{
	            	win.getLoader().load({  
	                    url : './getArticleStoreInfoById?id='+newId
	            	});
	            	currentId = newId;
       			}
	}else if(key == 'b' && win != null && win != 'undefined' && currentId != null){
		// before
            	var newId = getId(1,currentId);
            	if(newId == null || newId == ''){
            		Ext.example.msg('', '无数据', '');
            	}else{
	            	win.getLoader().load({  
	                    url : './getArticleStoreInfoById?id='+newId
	                });
	                currentId = newId;
            	}
	}else if(e.which == '13' && win != null && win != 'undefined' && currentId != null){
		// sync
        syncArticle();    	
	}else if(key == 'c' && win != null && win != 'undefined' && currentId != null){
		// hot tuijian
		if(!$("#hot").attr("checked")){
	        $("#hot").attr("checked",true);
		}else{
			$("#hot").attr("checked",false);
		}
	}else if(key == 's' && win != null && win != 'undefined' && currentId != null){
		// select menu
		$("#menuId").focus();
	}else if(key == 'd' && win != null && win != 'undefined' && currentId != null){
		// delete 
		Ext.Ajax.request({
					url : "deleteArticleStoreById",
					params : {
						id : currentId
					},
					type : "POST",
					timeout : 4000,
					success : function(response, opts) {
						var result = eval('('+response.responseText+')');
						if(result.resultCode == 'success'){
							search();
							Ext.example.msg('', '删除成功', '');
						}else{
							Ext.example.msg('', '删除失败', '');
						}
					}
				});
				
            	// 删除后获取上一个
            	var newId = getId(1,currentId);
            	if(newId == null || newId == ''){
            		Ext.example.msg('', '无数据', '');
            	}else{
	            	win.getLoader().load({  
	                    url : './getArticleStoreInfoById?id='+newId
	                });
	                currentId = newId;
            	}
	}
	//alert("ascii="+e.which+"\nkeychar="+String.fromCharCode(e.which));
});

function showErrorMsg(msg){
	Ext.example.msg('', msg, '');
}

// 获取站点列表
var getAllSiteStore = Ext.create('Ext.data.Store', {
     model: 'app.model.SiteModel',
     proxy: {
         type: 'ajax',
         url: 'getAllSiteList?type=1',
         reader: {
             type: 'json',
             root: 'data'
         }
     },
     autoLoad: false
 });

// 根据站点获取分类
var getCategoryBySiteIdStore = Ext.create('Ext.data.Store', {
    model: 'app.model.SiteCategoryModel',
    proxy: {
        type: 'ajax',
        url: 'getCategoryBySiteId?siteId=-1',
        reader: {
            type: 'json',
            root: 'data'
        }
    },
    autoLoad: false
});

var tbar = Ext.create('Ext.toolbar.Toolbar', {
	dock : 'top',
	layout: {  
        overflowHandler: 'Menu'  
    },  
	items : [{
		id:'siteId',
		xtype : 'combo',
		fieldLabel : '站点',
		labelWidth : 30,
		store : getAllSiteStore,
		displayField : 'siteName',
		valueField : 'id',
		name : 'siteId',
		typeAhead:false,
		editable:false,
		triggerAction : 'all',
		emptyText : '===请选择===',
		anchor : '95%',
		width : 170,
		listeners:{
	        'change': function(val){
	        				var siteId = val.value;
	        				getCategoryBySiteIdStore.proxy.url = 'getCategoryBySiteId?siteId='+siteId,
	        				getCategoryBySiteIdStore.load({
	        				    scope: this,
	        				    callback: function(records, operation, success) {
	        				    	if(records[0] != null){
	        				    		Ext.getCmp("siteCategoryId").select(records[0].raw.id);
	        				    		return;
	        				    	}
	        				    }
	        				});
	        		  }
	    }
	},{
		id:'siteCategoryId',
		xtype : 'combo',
		fieldLabel : '分类',
		labelWidth : 30,
		store : getCategoryBySiteIdStore,
		displayField : 'categoryName',
		valueField : 'id',
		name : 'siteCategoryId',
		typeAhead:false,
		editable:false,
		triggerAction : 'all',
		emptyText : '===请选择===',
		anchor : '95%',
		width : 170
	},{
		id:'type',
		xtype : 'combo',
		fieldLabel : '是否有图',
		labelWidth : 60,
		store : [	['0', '全部'],
					['1', '无图'],
	                ['2', '有图']],
		name : 'type',
		valueField : 'id',
		typeAhead:false,
		editable:false,
		value:'0',
		triggerAction : 'all',
		emptyText : '==请选择==',
		anchor : '95%',
		width : 150
	},{
		id:'statue',
		xtype : 'combo',
		fieldLabel : '是否同步',
		labelWidth : 60,
		store : [	['-1', '全部'],
					['0', '未同步'],
	                ['1', '已同步'],
	                ['2', '不可用'],
	                ['3', '同步中']],
		name : 'statue',
		valueField : 'id',
		typeAhead:false,
		editable:false,
		value:'-1',
		triggerAction : 'all',
		emptyText : '==请选择==',
		anchor : '95%',
		width : 150
	},{
		id:'content',
		xtype : 'textfield',
		name : 'content',
		fieldLabel : '内容关键字',
		labelWidth : 70,
		width : 300,
		emptyText : '========请填写关键字========'
	},{
		text : '查询',
		handler : function() {
			search();
		}
	},{
		text : '重置',
		handler : function() {
			var siteId = Ext.getCmp("siteId").getValue();
			if(siteId == null || siteId == '-1' || siteId == ''){
				
			}else{
				Ext.getCmp("siteId").select(-1);
			}
		
			Ext.getCmp("type").setValue("0");
			Ext.getCmp("statue").setValue("-1");
			Ext.getCmp("content").setValue("");
			search();
		}
	},{
		text : '批量同步',
		handler : function() {
			batchSync();
		}
	}]
});

function search(){
	var content = encodeURIComponent(Ext.getCmp("content").getValue());
	var siteId = Ext.getCmp("siteId").getValue();
	var siteCategoryId = Ext.getCmp("siteCategoryId").getValue();
	var type = Ext.getCmp("type").getValue();
	var statue = Ext.getCmp("statue").getValue();
	
	// 获取grid的store
	var articleStore = Ext.getCmp("articleStoreGrid").getStore();
	articleStore.load({
		params : {
			content : content,
			siteId:siteId,
			siteCategoryId : siteCategoryId,
			type:type,
			statue:statue,
			page : 1,
			start : 0,
			limit : 20
        }
	});
	articleStoreGrid.currentPage=1
}

var grid = Ext.define("app.view.ArticleStoreGrid", {
			extend : "Ext.grid.Panel",
			xtype: 'cell-editing',
			alias : "widget.articleStoreGrid",
			id : "articleStoreGrid",
			width:700,
			height:350,
			viewConfig:{
		         loadMask:false  // grid去掉加载中的提示
		    },
			selModel : {
				selType : "checkboxmodel"
			},
			border : 0,
			multiSelect : true,
			frame : false, // 不要边框
			tbar : tbar,
			bbar : {
				xtype : 'pagingtoolbar',
				store : 'ArticleStoreStore',
				dock : 'bottom',
				displayInfo : true
			},
			viewConfig:{  
		        enableTextSelection:true  // 文本可选择
		    },
			enableKeyNav : true,
			columnLines : true,
			forceFit :true, // 宽度自适配
			columns : [{
						text:"序号",
						dataIndex:"id",
						width:26
					},{
						text : "段子内容",
						dataIndex : "content",
						width : 170,
		                editor: {
		                	xtype : "textfield",
		                    allowBlank: false
		                }
					},{
						text : "唯一标识",
						dataIndex : "uniqueId",
						width : 70,
		                editor: {
		                	xtype : "textfield",
		                    allowBlank: false
		                }
					},{
						text : "是否有图",
						dataIndex : "type",
						width : 36,
						editor : {
			                xtype : 'combobox',
			                editable : false,
			                store : [['1', '无图'],
	                         ['2', '有图']]
						},
						renderer : function(v, p, record, rowIndex, colIndex) { // 值自定义渲染
					        if(v == '1'){
					        	return "无图";
					        }else if(v == '2'){
					        	return "有图";
					        }
					    }
					},{
						text : "源站",
						dataIndex : "siteName",
						width : 35,
						editor : {
							xtype : "textfield",
		                    allowBlank: false
			            }
					},{
						text : "分类",
						dataIndex : "siteCategoryName",
						width : 35,
						editor : {
							xtype : "textfield",
		                    allowBlank: false
			            }
					},{
						text : "状态",
						dataIndex : "statue",
						width : 26,
						editor : {
			                xtype : 'combobox',
			                editable : false,
			                store : [['0', '未同步'],
	                         ['1', '已同步'],
	                         ['2', '不可用']
			            ]},
						renderer : function(v, p, record, rowIndex, colIndex) { // 值自定义渲染
					        if(v == '0'){
					        	return "未同步";
					        }else if(v == '1'){
					        	return "<font style='color:red'>已同步</font>";
					        }else if(v == '2'){
					        	return "不可用";
					        }else if(v == '3'){
					        	return "<font style='color:red'>同步队列中</font>";
					        }
					    }
					},{
						text : "抓取时间",
						dataIndex : "createTime",
						width : 60,
						editor : {
							xtype : "textfield",
		                    allowBlank: false
			            }
					},{
		                xtype: 'actioncolumn',
		                width: 35,
		                tdCls: 'action',  
		                text: '操作',  
		                sortable: false,
		                menuDisabled: true,
		                items: [{
		                	icon: 'js/ext-4.2/resources/ext-theme-neptune/images/icon/add.png',
		                    tooltip: '处理',
		                    scope: this,
		                    handler: function(grid, rowIndex, colIndex) {
		                    	var record = grid.getStore().getAt(rowIndex);
		                        var id = record.get('id');
		                        this.loadArticleById(grid,id);
		                    },
		                    getClass: function(v, meta, record) {
		                    	return '';
		                    }
		                }
		                ]
		            }],
			listeners: { 
				itemdblclick:function(grid,row){
		            var id = row.data.id;
		            loadArticleById(grid,id);
		        }
			},					
			initComponent : function() {
				// 可编辑插件
				this.callParent(arguments);
			},
			store : "ArticleStoreStore"
});


// 同步仓库段子
function syncArticleStore(grid,id){
	var store = grid.getStore();
	Ext.Ajax.request({
		url : "syncArticleStore",
		params : {
			id : id
		},
		type : "POST",
		timeout : 4000,
		success : function(response, opts) {
			var result = eval('('+response.responseText+')');
			if(result.resultCode == 'success'){
				// 刷新grid
				search();
				Ext.example.msg('', '删除成功', '');
			}else{
				Ext.example.msg('', '删除失败', '');
			}
		}
	});
}

// 根据id删除段子
function deleteArticleStoreById(grid,id){
	var store = grid.getStore();
	Ext.Ajax.request({
		url : "deleteArticleStoreById",
		params : {
			id : id
		},
		type : "POST",
		timeout : 4000,
		success : function(response, opts) {
			var result = eval('('+response.responseText+')');
			if(result.resultCode == 'success'){
				// 刷新grid
				search();
				Ext.example.msg('', '删除成功', '');
			}else{
				Ext.example.msg('', '删除失败', '');
			}
		}
	});
}

function loadArticleById(grid,id){
	var store = grid.getStore();
	currentId = id;
	win = Ext.create('Ext.window.Window', {
		id:'articleStoreInfoId',
    	autoShow: false,
        title: '段子详情',
        width: 484,
        height: 483,
        minWidth: 300,
        minHeight: 200,
        layout: 'fit',
        plain:true,
        modal: 'true',  // 模态
        collapsible: true, //允许缩放条  
        closeAction: 'destroy',  
        autoScroll: true,
        maximizable :true,
        loader: {
            url:'getArticleStoreInfoById?id='+currentId,
            scripts: true,
            autoLoad: true
        },
        listeners:{
        	'beforerender':function(){
        		//myMask.show();  
        	}
       },
        buttonAlign: "center",  
        buttons: [{
            text: '上一个',
            handler: function() {
            	// 获取上一个
            	var newId = getId(1,id);
            	if(newId == null || newId == ''){
            		Ext.example.msg('', '无数据', '');
            	}else{
	            	win.getLoader().load({  
	                    url : './getArticleStoreInfoById?id='+newId
	                });
	                id = newId;
            	}
            }
        },{
            text: '关闭',
            handler: function() {
            	win.close();
            }
        },{
            text: '下一个',
            handler: function() {
            	// 获取下一个
            	var newId = getId(2,id);
            	if(newId == null || newId == '' || newId == 'null'){
            		Ext.example.msg('', '无数据', '');
            	}else{
	            	win.getLoader().load({  
	                    url : './getArticleStoreInfoById?id='+newId
	                });
	                id = newId;
            	}
            }
        }]
    });
    
    win.show();
}

function getId(orient,value){
	var id = 0;
	var content = encodeURIComponent(Ext.getCmp("content").getValue());
	var siteId = Ext.getCmp("siteId").getValue();
	var siteCategoryId = Ext.getCmp("siteCategoryId").getValue();
	var type = Ext.getCmp("type").getValue();
	var statue = Ext.getCmp("statue").getValue();
	
	Ext.Ajax.request({
			url : "getArticleStoreId",
			params : {
				id:value,
				content:content,
				siteId:siteId,
				siteCategoryId:siteCategoryId,
				type:type,
				orient:orient,
				statue:statue
			},
			type : "POST",
			timeout : 4000,
			async:false,
			success : function(response, opts) {
				var obj = eval('('+response.responseText+')');
				id = obj.data;
			}
	});
	
	return id;
}

function batchSync(){
	var grid = Ext.getCmp("articleStoreGrid");
	var store = grid.getStore();
	var records = grid.getSelectionModel().getSelection();
	
	var data = [];
	var model = store.model;
	Ext.Array.each(records, function(model) {
		if(model.get("id")!='0' && model.get("statue")=='0'){
			data.push(model.get("id"));
		}/*else{
			store.remove(model);
		}*/
	});
	if (data.length > 0) {
		var win = Ext.create('Ext.window.Window', {
	    	autoShow: false,
	        title: '批量同步',
	        width: 280,
	        height: 150,
	        layout: 'fit',
	        plain:true,
	        modal: 'true',  // 模态
	        collapsible: true, //允许缩放条  
	        closeAction: 'destroy',  
	        autoScroll: true,
	        maximizable :true,
	        loader: {
	            url:'getSyncMenuList',
	            scripts: true,
	            autoLoad: true
	        },
	        listeners:{
	        	'beforerender':function(){
	        		//myMask.show();  
	        	}
	       },
	        buttonAlign: "center",  
	        buttons: [{
	            text: '同步',
	            handler: function() {
	            	var ids
	            	Ext.Ajax.request({
						url : "batchSyncArticleStore",
						params : {
							ids : "" + data.join(",") + "",
							menuId : $("#menuId").val()
						},
						type : "POST",
						timeout : 8000,
						success : function(response, opts) {
							var result = eval('('+response.responseText+')');
							if(result.resultCode == 'success'){
								search();
								win.close();
								Ext.example.msg('', '批量同步成功', '');
							}else{
								Ext.example.msg('', '批量同步失败', '');
							}
						}
					});
	            }
	        }]
	    });
	    win.show();
	} else {
		Ext.example.msg('', '请选择未同步数据', '');
	}
}
